package com.trust.walletcore.example.utils

import android.util.Base64
import android.util.Log
import com.google.protobuf.ByteString
import com.solana.signer.SolanaSigner
import wallet.core.java.AnySigner
import wallet.core.jni.Base58
import wallet.core.jni.CoinType
import wallet.core.jni.HDWallet
import wallet.core.jni.PrivateKey
import wallet.core.jni.SolanaAddress



import wallet.core.jni.proto.Solana

import java.math.BigInteger

object SolanaTransactionHelper {




    fun createSolanaTransaction() {
        // 1. 初始化钱包并生成私钥
        val wallet = HDWallet(128, "") // 随机生成助记词
        val privateKey = wallet.getKeyForCoin(CoinType.SOLANA)
        val senderAddress = CoinType.SOLANA.deriveAddress(privateKey)

        println("Sender Address: $senderAddress")

        // 2. 配置交易参数
        val recipientAddress ="6zMNYYnqdVorfvmPHQNKz9D33iDeWahVHbdoKFTPc8xY"// // 替换为接收方地址
        val recentBlockhash = "BlockhashHere" // 从 Solana 网络获取最新区块哈希 SolanaTransactionSender()getRecentBlockhash
        val amount = 1000000L;//BigInteger.valueOf(1000000) // 转账金额（1 SOL = 10^9 Lamports）

//        // 3. 构建 Solana Transfer 指令
//        val transferMessage = Solana.Transfer.newBuilder().apply {
//            this.recipient = recipientAddress
//            this.value = amount
//        }.build()
//
//        // 4. 构建 Solana 交易消息
//        val transactionMessage = com.solana.transaction.Transaction.from(transferMessage.toByteArray())

        //构建交易消息
        val transferMessage = Solana.Transfer.newBuilder().apply {
            //sender = PrivateKey(senderPrivateKey).getPublicKeyEd25519().data().toBase58() // 发送地址
            recipient = recipientAddress
            value = amount
            // recentBlockhash = recentBlockhash
            // 注意：实际需要更复杂的指令序列化，此处为简化示例
        }.build()



        // 5. 签名交易
        val signingInput = Solana.SigningInput.newBuilder().apply {
            this.privateKey = ByteString.copyFrom(privateKey.data())
            this.transferTransaction = transferMessage
            this.recentBlockhash = recentBlockhash

        }.build()




        val signingOutput = AnySigner.sign(signingInput, CoinType.SOLANA, Solana.SigningOutput.parser())
        val signedTransaction = signingOutput.encoded.toByteArray()

        // 6. 输出交易对象和签名结果
        println("Signed Transaction (Base64): ${android.util.Base64.encodeToString(signedTransaction, android.util.Base64.NO_WRAP)}")
    }

//    // 2. 构建 Solana 转账交易并签名
//    fun signSolanaTransaction(
//        senderPrivateKey: ByteArray, // 发送方私钥
//        receiverAddress: String,     // 接收地址（Base58 格式）
//        amountLamports: Long,        // 转账金额（lamports）
//        recentBlockhash: String      // 从 RPC 获取的区块哈希
//    ): String {
//        // ---------------------- 核心步骤：构建交易消息 ----------------------
//        val transferMessage = Solana.Transfer.newBuilder().apply {
//            //sender = PrivateKey(senderPrivateKey).getPublicKeyEd25519().data().toBase58() // 发送地址
//            recipient = receiverAddress
//            value = amountLamports
//           // recentBlockhash = recentBlockhash
//            // 注意：实际需要更复杂的指令序列化，此处为简化示例
//        }.build()
//
//        // ---------------------- 使用 TrustWalletCore 签名 ----------------------
//        val signingInput = Solana.SigningInput.newBuilder().apply {
//            privateKey = ByteString.copyFrom(senderPrivateKey)
//            this.recentBlockhash = recentBlockhash
//            this.transferTransaction = transferMessage // 原始交易消息
//        }.build()
//
//        val signingOutput = AnySigner.sign(signingInput, CoinType.SOLANA, Solana.SigningOutput.parser())
//
//        // ---------------------- 组合签名和交易消息 ----------------------
//    //    val signedTx = signingOutput.signature.toByteArray() + transferMessage
//        return Base64.encodeToString(signedTx, Base64.NO_WRAP)
//    }

    // 3. 工具函数：字节数组转 Base58 地址
    fun ByteArray.toBase58(): String {
        return Base58.encode(this)
    }






//    fun signTransaction(
//        wallet: HDWallet,
//        recipientAddress: String?,
//        amountInLamports: Long
//    ): String? {
//        try {
//            // 创建目标地址
//            val recipient = SolanaAddress(recipientAddress)
//
//            // 构建 Solana 交易
//            val transaction: SolanaTransaction = SolanaTransaction()
//            transaction.addInstruction(
//                SolanaTransaction.transferInstruction(
//                    wallet.getAddress(),
//                    recipient,
//                    amountInLamports
//                )
//            )
//
//            // 获取 Solana 签名器
//            val signer = SolanaSigner(wallet)
//
//            // 签署交易
//            val signedTransaction = signer.signTransaction(transaction)
//
//            // 返回签名后的交易（十六进制字符串）
//            return Data.toHexString(signedTransaction)
//        } catch (e: Exception) {
//            e.printStackTrace()
//            return null
//        }
//    }
}

